﻿using UnityEngine;
using System.Collections;

public class DynamicMeshCollider : PhysicCollider {

    SkinnedMeshRenderer sk;
    Mesh bakedMesh;
    protected override void Awake()
    {
        base.Awake();
        colliderType = ColliderType.DynamicMesh;
    }

    // Use this for initialization
    void Start () {
        sk = GetComponent<SkinnedMeshRenderer>();
        //bakedMesh = new Mesh();
        PhysicSystem.Instance.AddCollider(this);
	}
	
	// Update is called once per frame
	void Update () {
        //sk.BakeMesh(bakedMesh);
	}

    private void OnDrawGizmos()
    {
        if (IsCollision)
        {
            var newMesh = new Mesh();
            sk.BakeMesh(newMesh);
            var vertices = newMesh.vertices;
            var mat = Math.LocalToWorldUnScale(transform);

            for(var i = 0; i < vertices.Length; i++)
            {
                var worldPos = mat.MultiplyPoint3x4(vertices[i]);
                vertices[i] = worldPos;
            }
            newMesh.vertices = vertices;
            Gizmos.color = Color.red;
            Gizmos.DrawMesh(newMesh);
        }
    }

    public System.Collections.Generic.IEnumerable<Triangle> GetTriangles()
    {
        bakedMesh = new Mesh();
        sk.BakeMesh(bakedMesh);
        var count = bakedMesh.triangles.Length;
        var triangles = bakedMesh.triangles;
        var vertex = bakedMesh.vertices;
        var mat = Math.LocalToWorldUnScale(transform);
        for(var i = 0; i < count/3; i++)
        {
            var v0 = triangles[i * 3 + 0];
            var v1 = triangles[i * 3 + 1];
            var v2 = triangles[i * 3 + 2];


            var tri = new Triangle(mat.MultiplyPoint3x4(vertex[v0]), mat.MultiplyPoint3x4(vertex[v1]), mat.MultiplyPoint3x4(vertex[v2]));
            yield return tri;
        }
    }

}
